package org.openfans.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Feed;
import org.openfans.util.ThreadFans;
import org.openfans.util.WebUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.BaseCommandController;

/**
 * Desc：subscribe or Unsubscribe feed<br>
 * Date：2007-1-24<br>
 * 
 * @author pesome<br>
 * @email:pesome@gmail.com<br>
 */
public class FansSubFeedController extends BaseCommandController {
	private Facade facade;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		WebUtil.letNoCache(response);

		String type = request.getParameter("type");
		String feedId = request.getParameter("id");

		doAction(type, Integer.parseInt(feedId));
		return new ModelAndView("redirect:listFansSubFeed.ajax");
	}

	private void doAction(String type, int feedId) {
		if (("sub").equals(type)) {
			subFeed(feedId);
		} else if ("unsub".equals(type)) {
			unsubFeed(feedId);
		}
	}

	private String subFeed(int feedId) {
		Feed feed = facade.getFeed(feedId);
		try {
			facade.addFansSubFeed(facade.getFans(ThreadFans.get().getFansId()),
					feed);
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "ok";
	}

	private String unsubFeed(int feedId) {
		Feed feed = facade.getFeed(feedId);
		try {
			facade.removeFansSubFeed(facade.getFans(ThreadFans.get()
					.getFansId()), feed);
			return "ok";
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

	}

}
